package com.xmqian.app.common.utils;

import android.support.annotation.NonNull;

import com.coszero.utilslibrary.utils.LogX;
import com.coszero.utilslibrary.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.util.List;

/**
 * Desc: google的Gson解析
 * com.google.code.gson:gson:2.8.2
 * <p>
 * Author xmqian
 * Email:xmqian93@163.com
 * Date: 2019/5/17
 */
public class GsonUtil {
    private static GsonBuilder gsonBuilder = null;

    private static Gson getGson() {
        GsonBuilder gsonBuilder = getGsonBuilder();
        return gsonBuilder.create();
    }

    @NonNull
    private static GsonBuilder getGsonBuilder() {
        if (gsonBuilder == null) {
            gsonBuilder = new GsonBuilder();
        }
        return gsonBuilder;
    }

    /**
     * 将对象转化为字符串
     */
    public static String toJsonStr(Object obj) {
        String jsonStr = getGson().toJson(obj);
        return jsonStr;
    }

    /**
     * 字符串转化为list
     *
     * @param listJson
     * @param type new TypeToken<ArrayList<CityBean>>() {}.getType()
     * @return
     */
    public static List getList(String listJson, Type type) {
        try {
            if (!StringUtils.isEmpty(listJson)) {
                List listBeans = getGson().fromJson(listJson, type);
                return listBeans;
            }
        } catch (Exception e) {
            LogX.e("GsonUtil->getPlazzList()", "解析数组json失败");
        }
        return null;
    }
}
